package com.jinlejia.bbs.http.utils;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.util.LogUtil;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.bean.Clients;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DbUtil;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.alibaba.fastjson.JSON.parseObject;

/**
 * Created by Administrator on 2017/9/22 0022.
 */

public class ContactsUtils {

    private static ContactsUtils instance;
    private static Context context;

    public static ContactsUtils getInstance(Context c) {
        if (null == instance) {
            instance = new ContactsUtils();
            context = c;
        }
        return instance;
    }

    public ArrayList<Clients> getContactList() {
        String url = ApiConfig.CONTACTS_LIST;
        if (null != ACache.get(context).getAsString("update_time")) {
            url = url.concat("?updateTime=").concat(ACache.get(context).getAsString("update_time"));
        }
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if ( Integer.parseInt(response.get("code").toString()) == 200 ) {
                            //减去一分钟数据请求时间
                            String updateTime = DateUtil.getTime(System.currentTimeMillis() - 60 * 1000, "yyyy-MM-dd HH:mm:ss");
                            ACache.get(context).put("update_time", updateTime);
                            JSONObject data = parseObject(response.get("data").toString());

                            // 应用迭代器Iterator 获取所有的key值
                            Iterator iterator = data.keySet().iterator();
                            while (iterator.hasNext()) { // 遍历每个key
                                String key = (String) iterator.next();
                                ArrayList<Clients> cList = parseObject(data.getJSONArray(key).toString(), new TypeReference<ArrayList<Clients>>() {
                                });

                                    Observable.from(cList)
                                            .map(new Func1<Clients, Clients>() {
                                                @Override
                                                public Clients call(Clients answer) {
                                                    DbUtil.getDB(context).single().delete(WhereBuilder.create(Clients.class, "pin=?", new String[]{answer.getPin()}));
                                                    answer.setSortLetters(answer.getPin().substring(0,1));
                                                    DbUtil.getDB(context).single().save(answer);
//                                                    System.out.println( c.toString() );
                                                    return answer;
                                                }
                                            }).subscribeOn(Schedulers.io())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe();
                                }
                            }
                    }
                });

        return DbUtil.getDB(context).query(Clients.class);
    }

}
